package com.hdu.suixianglu;

public class lc59 {
    class Solution {
        int cur = 1;
        int[][] ans;
        public int[][] generateMatrix(int n) {
            ans = new int[n][n];
            int a = 0;
            int b = 0;
            int c = n - 1;
            int d = n - 1;
            while (a < c && b < d)
            {
                handle(a, b, c, d);
                a++;
                b++;
                c--;
                d--;
            }
            return ans;
        }

        void handle(int a, int b, int c, int d)
        {
            if (a == c)
            {
                for (int i = b; i <= d; i++)
                {
                    ans[a][i] = cur++;
                }
            }
            else if (b == d)
            {
                for (int i = a; i <= c; i++)
                {
                    ans[i][b] = cur++;
                }
            }
            else
            {
                for (int i = b; i < d; i++)
                {
                    ans[a][i] = cur++;
                }
                for (int i = a; i < c; i++)
                {
                    ans[i][d] = cur++;
                }
                for (int i = d; i > b; i--)
                {
                    ans[c][i] = cur++;
                }
                for (int i = c; i > a; i--)
                {
                    ans[i][b] = cur++;
                }
            }
        }
    }
}
